package com.central.scheduler.plugin.task.api;

import com.central.scheduler.spi.task.AbstractTask;
import com.central.scheduler.spi.task.request.TaskRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.StringJoiner;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Tindy
 * @date 2021/11/15
 * @describe
 */
public abstract class AbstractTaskExecutor extends AbstractTask {

    public static final Marker FINALIZE_SESSION_MARKER = MarkerFactory.getMarker("FINALIZE_SESSION");

    protected Logger logger;


    /**
     * constructor
     *
     * @param taskRequest taskRequest
     */
    protected AbstractTaskExecutor(TaskRequest taskRequest) {
        super(taskRequest);
        logger = LoggerFactory.getLogger(taskRequest.getTaskLogName());
    }

    /**
     * log handle
     *
     * @param logs log list
     */
    public void logHandle(LinkedBlockingQueue<String> logs) {
        // note that the "new line" is added here to facilitate log parsing
        if (logs.contains(FINALIZE_SESSION_MARKER.toString())) {
            logger.info(FINALIZE_SESSION_MARKER, FINALIZE_SESSION_MARKER.toString());
        } else {
            StringJoiner joiner = new StringJoiner("\n\t");
            while (!logs.isEmpty()) {
                joiner.add(logs.poll());
            }
            logger.info(" -> {}", joiner);
        }
    }



    public static void wgetCommand(String url,String execLocalPath) throws IOException, InterruptedException {
        List<String> command = new LinkedList<>();
        //init process builder
        ProcessBuilder processBuilder = new ProcessBuilder();
        // setting up a working directory
        processBuilder.directory(new File(execLocalPath));
        // merge error information to standard output stream
        processBuilder.redirectErrorStream(true);
        // setting commands
        command.add("wget");
        command.addAll(Collections.emptyList());
        command.add(url);
        command.addAll(Collections.emptyList());
        command.add("-P");
        command.addAll(Collections.emptyList());
        command.add(execLocalPath);
        // setting up user to run commands
        processBuilder.command(command);
        processBuilder.start().waitFor();
    }
}

